package com.bz.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bz.content.service.ContentCategoryService;
import com.bz.mapper.TbContentCategoryMapper;
import com.bz.pojo.TbContentCategory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContentCategoryServiceImpl extends ServiceImpl<TbContentCategoryMapper, TbContentCategory> implements ContentCategoryService {

    @Override
    public List<TbContentCategory> selectContentCategoryByParentId(Long parentId) {
        QueryWrapper<TbContentCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(parentId != null,TbContentCategory::getParentId,parentId)
                             .eq(TbContentCategory::getStatus,1);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public Integer insertContentCategory(TbContentCategory tbContentCategory) {
        QueryWrapper<TbContentCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(tbContentCategory.getParentId() != null,TbContentCategory::getId,tbContentCategory.getParentId())
                             .eq(TbContentCategory::getStatus,1);
        TbContentCategory contentCategory = this.baseMapper.selectOne(queryWrapper);
        if (contentCategory != null && !contentCategory.getIsParent()){
            contentCategory.setIsParent(true);
            contentCategory.setParentId((long)0);
        }
        Date date = new Date();
        tbContentCategory.setCreated(date);
        tbContentCategory.setUpdated(date);
        tbContentCategory.setIsParent(false);
        return this.baseMapper.insert(tbContentCategory);
    }

    @Override
    public Integer deleteContentCategoryById(TbContentCategory tbContentCategory) {
        // 查询子节点
        QueryWrapper<TbContentCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(tbContentCategory.getId() != null,TbContentCategory::getParentId,tbContentCategory.getId())
                             .eq(TbContentCategory::getStatus,1);
        List<TbContentCategory> list = this.baseMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0){
            list.add(tbContentCategory);
            list.forEach(x -> {
                x.setStatus(2);
                this.deleteContentCategoryById(x);
                this.updateContentCategoryById(x);
            });
            return 200;
        }else {
            return this.updateContentCategoryById(tbContentCategory);
        }
    }

    @Override
    public Integer updateContentCategoryById(TbContentCategory tbContentCategory) {
        tbContentCategory.setUpdated(new Date());
        return this.baseMapper.updateById(tbContentCategory);
    }
}
